package customtype

import (
	"database/sql/driver"
	"errors"
	"fmt"
	"time"
)

const TimeFormat = "2006-01-02 15:04:05"

// 时间格式化类型
type LocalTime time.Time

func (t LocalTime) Value() (driver.Value, error) {
	return time.Time(t), nil
}

func (t *LocalTime) Scan(v interface{}) error {
	switch vt := v.(type) {
	case int64:
		*t = LocalTime(time.Unix(vt, 0))
	case time.Time:
		*t = LocalTime(vt)
	case string:
		loc, _ := time.LoadLocation("local")
		tt, _ := time.ParseInLocation(TimeFormat, vt, loc)
		*t = LocalTime(tt)

	default:
		return errors.New("类型处理错误")
	}
	return nil
}

func (t LocalTime) MarshalJSON() ([]byte, error) {
	tTime := time.Time(t)
	tStr := tTime.Format(TimeFormat) // 设置格式
	// 注意 json 字符串风格要求
	return []byte(fmt.Sprintf("\"%v\"", tStr)), nil
}

func (m *LocalTime) UnmarshalJSON(data []byte) error {
	if string(data) == "null" || string(data) == `""` {
		return nil
	}
	// Fractional seconds are handled implicitly by Parse.
	tt, err := time.Parse(`"`+TimeFormat+`"`, string(data))
	*m = LocalTime(tt)
	return err
}
